<template>
  <div class="padding-20">
    <div class="bg-white padding-top-30 padding-bottom-15 padding-left-right-20" id="baseInfo">
      <form-common :filed-list="contractThrowList" ref="form" @rightBtnFn="rightBtnFn"></form-common>
    </div>

    <!-- 退租信息 -->
    <div class="bg-white padding-left-right-20 padding-top-20 margin-top-20">
      <div class="font-weight-700 font-size-18 padding-bottom-10">退租信息</div>
      <form-common :filed-list="throwList" ref="throw" @selectChange="selectChange"></form-common>
    </div>

    <!-- 合同文件 -->
    <div class="bg-white padding-left-right-20 padding-top-20 margin-top-20">
      <div class="font-weight-700 font-size-18 padding-bottom-10">合同文件</div>
      <contract-file ref="file" :contract-info="contractInfo" :contract-type="contractType"></contract-file>
    </div>

    <!-- 账单 -->
    <div v-if="!$route.query.taskId && contractCategory == 1" class="bg-white padding-left-right-20 padding-top-20 margin-top-20">
      <div class="font-weight-700 font-size-18 padding-bottom-10">新增账单</div>
      <el-table :border="true" :data="billList">
        <el-table-column v-if="contractType == 'WRSB'" label="无人设备" prop="chargeItemName" />
        <template v-else-if="contractType == 'QTSR'">
          <!-- <el-table-column label="经营事项说明" prop="dictKeyName" /> -->
          <el-table-column label="收入类型" prop="chargeItemName" />
        </template>
        <el-table-column v-else label="资产名称" prop="chargeItemName" />
        <el-table-column align="left" label="账单周期">
          <template slot-scope="scope">
            <span>{{ scope.row.cycleStartTime | formatDateTime('YYYY-MM-DD') }}</span>
            <span>至</span>
            <span>{{ scope.row.cycleEndTime | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="应缴费时间">
          <template slot-scope="scope">
            <span>{{ scope.row.paymentDeadline | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="费项">
          <template slot-scope="scope">
            <span>{{ getBizTxt(scope.row.bizType) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="应收金额">
          <template slot-scope="scope">
            <span v-if="!isEdit">{{ scope.row.amountReceivable | fmoneyThousand }}</span>
            <el-input-number v-else :controls="false" class="no-border-input" v-model="scope.row.amountReceivable"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="t-center margin-top-20" v-if="isEdit">
      <el-button type="primary" size="mini" @click="submit">保存</el-button>
      <el-button type="primary" size="mini" @click="submit('audit')">提交</el-button>
    </div>

    <!-- 签约方 -->
    <el-dialog title="签约方" :visible.sync="signDialogShow" width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="border-b-line padding-top-bottom-15" v-for="item in contractInfo.partnerList" :key="item.primaryKey">
        <div>
          <span class="label-width font-size-16">签约方名称：</span>
          <span class="font-size-16">{{ item.partnerName || '--' }}</span>
        </div>
        <div class="flex justify-between padding-top-10">
          <div class="flex-1 padding-right-20">
            <span class="label-width font-size-16">付款银行：</span>
            <span class="font-size-16">{{ item.paymentBank || '--' }}</span>
          </div>
          <div class="flex-1">
            <span class="label-width font-size-16">付款账号：</span>
            <span class="font-size-16">{{ item.paymentAccount || '--' }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { contractThrowList, throwList } from './form';
  import { apiPactConstant } from '@a/index';
  import formCommon from '@g/components/form/formCommon.vue';
  import contractFile from '../drafts/contractFile.vue';
  import { apiContractReturnInfo, apiDictMoreList, apiProjectList, apiBillReturnList, apiBillReturnSave, apiBillReturnUpdate } from '../../../api/contract';
  import { requestTips, setFiledVal, askDialog } from '@/common/js/utils';
  import { apiCreateAudit } from '../../../api/common';
  import merge from 'webpack-merge';

  export default {
    name: 'contractThrowLease',
    data() {
      return {
        signDialogShow: false,
        contractThrowList: contractThrowList,
        throwList: throwList,
        contractCode: this.$route.query.contractCode,
        contractType: this.$route.query.contractType,
        contractKey: this.$route.query.contractKey,
        contractCategory: this.$route.query.contractCategory, //1,收入 2,支出
        contractInfo: {},
        constractStatusList: ['草稿', '审批中', '执行中', '驳回', '执行完毕', '已废止'],
        billList: [],
        billTypeList: [],
        userInfo: JSON.parse(localStorage.getItem('userInfo')),
      };
    },

    computed: {
      //是否可以编辑: 不在流程中 //contractStatus: 0 草稿 1 审批中 2 审批完成/履行中 3 驳回 4 履行完毕 5 已废止
      isEdit() {
        if (this.$route.query.isBack) {
          return true;
        } else {
          return !this.contractInfo.contractStatus || this.contractInfo.contractStatus == 3 ? true : false;
        }
      },
    },

    mounted() {
      this.getProjectList();
      this.getOptionList();
      this.getBillTypeList();
      this.getContractInfo();
    },

    // $route.query.isBack代表时新增
    methods: {
      //合同详情 新增入参 用contractCode  详情编辑时 用contractKey
      async getContractInfo(key) {
        let param = {};
        if (this.$route.query.isBack) {
          param = { contractCode: this.contractCode };
        } else {
          param = { primaryKey: key || this.contractKey };
        }
        let res = await apiContractReturnInfo(param);
        //签约方
        let partnerName = '';
        res.partnerList &&
          res.partnerList.forEach(item => {
            partnerName += item.partnerName + '，';
          });
        res.partnerName = partnerName.substring(0, partnerName.length - 1);
        //资产编号
        let assetName = '';
        res.rentCycleList &&
          res.rentCycleList.forEach(item => {
            assetName += item.assetName + '，';
          });
        res.assetName = assetName.substring(0, assetName.length - 1);
        if (this.$route.query.isBack) res.contractSignDate = '';
        if (!this.$route.query.isBack) {
          this.getReturnRentReason(res.returnRentType); //退款原因
        }
        this.billList = res.billList || [];
        this.contractInfo = res;
        this.$refs.form.initModel();
        this.$refs.throw.initModel();
        this.initBaseInfo();
        !this.isEdit && this.banFieldEdit();
      },

      //合同类型
      async getOptionList() {
        let res = await apiDictMoreList({ dictTypeList: ['contractType', 'return_rent_type'] });
        let contractTypeObj = res.rows.find(item => item.dictType == 'contractType');
        let returnRentTypeObj = res.rows.find(item => item.dictType == 'return_rent_type');
        this.contractThrowList.forEach(item => {
          if (item.bindFieldName == 'contractType') {
            item.optionList = contractTypeObj.dictList || [];
          }
        });
        this.throwList.forEach(item => {
          if (item.bindFieldName == 'returnRentType') {
            item.optionList = returnRentTypeObj.dictList || [];
          }
        });
      },

      //账单
      async getBillList(cycleEndTime) {
        let res = await apiBillReturnList({ contractCode: this.contractCode, cycleEndTime: cycleEndTime });
        this.billList = res.rows || [];
      },

      //项目信息
      async getProjectList() {
        let res = await apiProjectList();
        this.contractThrowList.forEach(item => {
          if (item.bindFieldName == 'projectKey') {
            item.optionList = res.rows || [];
          }
        });
      },

      //常量
      async getBillTypeList() {
        let res = await apiPactConstant();
        this.billTypeList = res.billType || [];
      },

      //退款原因
      async getReturnRentReason(key) {
        let res = await apiDictMoreList({ dictTypeList: [key] });
        this.throwList.forEach(item => {
          if (item.bindFieldName == 'returnRentReason') {
            item.optionList = res.rows[0].dictList || [];
          }
        });
      },

      //保存 ｜ 提交
      async submit(type) {
        if (type == 'audit') {
          await askDialog('确认提交？', () => {
            this.saveData(type);
          });
        } else {
          this.saveData();
        }
      },

      //保存数据入库
      async saveData(type) {
        let infoModel = this.$refs.form.validateForm();
        if (!infoModel) return;
        let throwModel = this.$refs.throw.validateForm();
        if (!throwModel) return;
        let fileData = this.$refs.file.saveFn(); //附件信息
        if (fileData === false) {
          return;
        }
        this.contractInfo.contractSignDate = infoModel.contractSignDate;
        let param = {
          ...this.contractInfo,
          ...throwModel,
        };
        //附件信息
        for (let i in fileData) {
          param[i] = fileData[i];
        }
        param.billList = this.billList;
        console.log(param);
        if (this.$route.query.isBack) {
          param.usedContractKey = this.contractInfo.primaryKey;
        }
        let res = this.$route.query.isBack ? await apiBillReturnSave(param) : await apiBillReturnUpdate(param);
        requestTips(res, () => {
          if (type == 'audit') {
            this.submitFn(res.key);
          } else {
            if (this.$route.query.isBack) {
              let param = { contractKey: res.key, isBack: '' };
              this.getContractInfo(res.key);
              this.$router.replace({
                query: merge(this.$route.query, param),
              });
            } else {
              this.getContractInfo();
            }
          }
        });
      },

      //提审方法 key:合同key
      async submitFn(key) {
        let param = {
          businessKey: key, //合同key
          userPrimaryKey: this.userInfo.key,
          projectKey: this.contractInfo.projectKey,
          type: '合同', //合同,账单,付款,合同终止
          typeKey: 'returnRent',
        };
        let res = await apiCreateAudit(param);
        requestTips(res, () => {
          let alterRouteParam = { contractKey: key, processWorkId: res.key };
          if (this.$route.query.isBack) alterRouteParam.isBack = '';
          this.$router.replace({
            query: merge(this.$route.query, alterRouteParam),
          });
          setTimeout(() => {
            window.location.reload(); //reload的原因是： 提审后更新路由的processWorkId参数 要展示审批信息的tab
          }, 500);
        });
      },

      //form数据回显
      initBaseInfo() {
        this.initStatusName();
        this.contractThrowList.forEach(item => {
          for (let i in this.contractInfo) {
            if (item.bindFieldName == i) {
              item.bindFieldVal = this.contractInfo[i];
            }
          }
        });
        this.throwList.forEach(item => {
          for (let i in this.contractInfo) {
            if (item.bindFieldName == i) {
              item.bindFieldVal = this.contractInfo[i];
            }
          }
        });
      },

      //禁止字段编辑
      banFieldEdit() {
        this.contractThrowList.forEach(item => {
          item.isReadOnly = true;
          item.isRequired = false;
          if (item.type == 'select' || item.type == 'date' || item.type == 'radio' || item.type == 'checkbox') {
            item.isDisabled = true;
          }
        });
        this.throwList.forEach(item => {
          item.isReadOnly = true;
          item.isRequired = false;
          if (item.type == 'select' || item.type == 'date' || item.type == 'radio' || item.type == 'checkbox') {
            item.isDisabled = true;
          }
        });
      },

      //赋值表单一些基础值
      initStatusName() {
        this.contractThrowList.forEach(item => {
          if (item.bindFieldName == 'statusName') {
            if (!this.contractInfo.contractStatus) {
              item.bindFieldVal = '草稿';
            } else {
              item.bindFieldVal = this.constractStatusList[Number(this.contractInfo.contractStatus)];
            }
          }
        });
      },

      //表单事件
      async selectChange(data) {
        //退租类型 -> 退租原因
        if (data.filedName == 'returnRentType') {
          let res = await apiDictMoreList({ dictTypeList: [data.filedVal] });
          data.cb('returnRentReason', '');
          data.cbList('returnRentReason', res.rows[0].dictList);
        }
        //退租时间 -> 账单
        if (data.filedName == 'returnEffectiveTime' && this.contractCategory == 1) {
          this.getBillList(data.filedVal);
        }
      },

      //账单的费项名
      getBizTxt(key) {
        let target = this.billTypeList.find(item => item.key == key);
        return target ? target.value : '';
      },

      rightBtnFn(data) {
        this.signDialogShow = true;
      },
    },

    components: { formCommon, contractFile },
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-form .el-form-item__label {
    padding-left: 0;
  }
</style>
